import Vue from 'vue'
import store from '../store/index'

export default (Vue) => {
  Vue.directive('permission', {
    inserted: function (el, binding, vnode) {
      const { value } = binding
      const roles = []
      if (store.getters && store.getters.user.identity) {
        roles.push(store.getters.user.identity)
      }

      if (value && value instanceof Array && value.length > 0) {
        const permissionRoles = value
        const hasPermission = roles.some(role => {
          return permissionRoles.includes(role)
        })
        if (!hasPermission) {
          el.parentNode && el.parentNode.removeChild(el)
        }
      } else {
        throw new Error(`need roles! Like v-permission="['admin', 'editor']"`)
      }
    }
  })
}
